function qp_inject()
{    
    if (document.body == null) return;
    
    var keyword = qp_getKeyword();
    if (keyword == null || keyword == "")
    {
        return;
    }
    if (keyword.length > 50)
    {
        alert("使用“豆瓣快看”查询时，关键字最多不能超过 50 个字符。");
        return;
    }
    
    qp_search(keyword);
}

function qp_getKeyword()
{
    selection = document.getSelection();
    if (document.getSelection() == null) return null;
    var keyword = qp_formatKeyword(selection.toString());
    return keyword;
}

function qp_formatKeyword(p_keyword)
{
    var keyword = p_keyword.replace(/\r/g, " ").replace(/\n/g, " ");
    keyword = keyword.replace("《", "").replace("》", " ");
    return keyword;
}




var _keyword = null;
var $qp_mask = null;
var $qp_frame = null;
var $qp_closeButton = null;
function qp_search(p_keyword)
{
    if (_keyword == p_keyword) return;
    _keyword = p_keyword;
    
    $qp_mask = $("body > #qp_mask");
    $qp_frame = $qp_mask.children("iframe:first");
    $qp_closeButton = $qp_mask.children("#close");
    if ($qp_mask.length == 0)
    {
        $qp_mask = $("<div id='qp_mask'/>");
        $qp_mask.click(qp_exit);
        
        $qp_frame = $("<iframe id='qp_frame' src='" + qp_path("popup.html") + "?keyword=" + encodeURIComponent(p_keyword) + "'/>");
        $qp_mask.append($qp_frame);
        
        $qp_closeButton = $("<img id='close' src='" + qp_path("themes/default/images/close_button.png") + "' title='关闭' style='position:absolute'/>");
        $qp_closeButton.click(qp_exit);
        $qp_mask.append($qp_closeButton);
    }
    $qp_frame.attr("src", qp_path("popup.html") + "?keyword=" + encodeURIComponent(p_keyword));
    $(document.body).append($qp_mask);
    $qp_frame.css("marginLeft", ($qp_mask.width() - $qp_frame.width()) / 2);
    $qp_frame.css("marginTop", ($qp_mask.height() - $qp_frame.height()) / 2);
    
    $qp_closeButton.css("top", ($qp_mask.height() - $qp_frame.height()) / 2 - 14);
    $qp_closeButton.css("left", ($qp_mask.width() - $qp_frame.width()) / 2 + $qp_frame.width() - 20);
    
    $qp_mask.fadeIn("fast");
}

function qp_exit()
{
    $qp_mask.slideUp("fast");
}

function qp_path(p_path)
{
    return chrome.extension.getURL(p_path);
}



qp_inject();